//
//  ICRCodeViewController.m
//  ICome
//
//  Created by zhangrongwu on 16/8/11.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICRCodeViewController.h"
#import "QRView.h"
#import "QRUtil.h"
#import "ICScanNative.h"
#import "TZImageManager.h"
#import "TZImagePickerController.h"
#import "ICHeaderFile.h"

@interface ICRCodeViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIButton *photoBtn;
@property (nonatomic, strong) QRView *qrView;
@property (nonatomic, strong)ICScanNative *scanObj;
@property (nonatomic, copy, readwrite) NSString *urlString;
@property (nonatomic, assign)CGRect cropRect;
@end

@implementation ICRCodeViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self drawScanView];
    self.view.backgroundColor = [UIColor blackColor];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MBProgressHUD showMessage:@"相机启动中..." toView:self.view];
    WEAKSELF
    [ICSystemTool checkCameraAuthorizationStatus:^{
        //不延时，可能会导致界面黑屏并卡住一会
        [weakSelf performSelector:@selector(startScan) withObject:nil afterDelay:0.3];
    }];
}

- (void)drawScanView {
    self.qrView.center = CGPointMake([QRUtil screenBounds].size.width / 2, [QRUtil screenBounds].size.height / 2);
    
    //修正扫描区域
    CGFloat screenHeight = self.view.frame.size.height;
    CGFloat screenWidth = self.view.frame.size.width;
    self.cropRect = CGRectMake((screenWidth - self.qrView.transparentArea.width) / 2 / App_Frame_Width,
                                 (screenHeight - self.qrView.transparentArea.height) / 2 / APP_Frame_Height,
                                 self.qrView.transparentArea.width/ App_Frame_Width,
                                 self.qrView.transparentArea.height/ APP_Frame_Height);
}

- (void)startScan {
    UIView *videoView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];
    videoView.backgroundColor = [UIColor clearColor];
    [self.view insertSubview:videoView atIndex:0];
    
    NSString *strCode = AVMetadataObjectTypeQRCode;
    WEAKSELF
    if (!self.scanObj) {
        self.scanObj = [[ICScanNative alloc] initWithPreView:videoView ObjectType:@[strCode]  cropRect:self.cropRect success:^(NSArray<ICScanResult *> *array) {
            NSLog(@"%@", array);
            if (array.count > 0) {
                ICScanResult *result = [array firstObject];
                weakSelf.urlString = result.strScanned;
                [weakSelf RCodeFinish];
            }
        }];
        [self.scanObj setNeedCaptureImage:NO];
    }
    [self.scanObj startScan];
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [self.scanObj stopScan];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)configUI {
    
    [self.view addSubview:self.qrView];
    [self.view addSubview:self.backBtn];
    [self.view addSubview:self.photoBtn];
}

- (void)backAction:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:NO];
//    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoAction:(UIButton *)button {

    [self pushImagePickerController];
}

- (void)RCodeFinish {

    if (![ICTools stringEmpty:self.urlString]) {
        [[IComMediator sharedInstance] toHandlerTargetName:@"Application" action:@"nativeFetchRCodeViewController" params:@{@"url":self.urlString}];
        [self backAction:nil];
    } else {
        ALERT(@"未能识别");
    }
}

#pragma mark - Getter and Setter
-(UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _backBtn.frame = CGRectMake(15, [ICTools getHomebarHeight] + 20, 50, 50);
        [_backBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

-(UIButton *)photoBtn {
    if (!_photoBtn) {
        _photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _photoBtn.frame = CGRectMake(App_Frame_Width - 60 - 15, [ICTools getHomebarHeight] + 20, 60, 50);
        [_photoBtn setTitle:@"照片" forState:UIControlStateNormal];
        [_photoBtn addTarget:self action:@selector(photoAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _photoBtn;
}


-(QRView *)qrView {
    if (!_qrView) {
        CGRect screenRect = [QRUtil screenBounds];
        _qrView = [[QRView alloc] initWithFrame:screenRect];
        float width = 280.0 / 375.0 * App_Frame_Width;
        _qrView.transparentArea = CGSizeMake(width, width);
        
        _qrView.backgroundColor = [UIColor clearColor];
    }
    return _qrView;
}


- (void)pushImagePickerController {
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:1 delegate:nil pushPhotoPickerVc:YES];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
//     imagePickerVc.minImagesCount = 1;
    // imagePickerVc.alwaysEnableDoneBtn = YES;
    
    // imagePickerVc.minPhotoWidthSelectable = 3000;
    // imagePickerVc.minPhotoHeightSelectable = 2000;
    
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = YES;
    imagePickerVc.allowCrop = NO;// 裁剪
//    imagePickerVc.needCircleCrop = NO;// 圆
//    imagePickerVc.circleCropRadius = 100;
    
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        // 处理
        [ICScanNative recognizeImage:[photos firstObject]  success:^(NSArray<ICScanResult *> *array) {
            NSLog(@"%@", array);
            if (array.count > 0) {
                ICScanResult *result = [array firstObject];
                self.urlString = result.strScanned;
                [self RCodeFinish];
            } else {
                ALERT(@"未发现二维码");
                [self backAction:nil];
            }
        }];
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
@end
